<template>
  <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 20px">
    <el-card shadow="never" class="box-card"
             style="margin: 0; border: none; flex-grow: 3; flex-basis: 0; padding: 0px">
      <div slot="header">
        <span>{{ meetingVO.name }}</span>
        <el-button style="float: right; padding: 3px 0" type="text">会议通知</el-button>
      </div>
      <el-descriptions class="margin-top" :model="meetingVO" size="mini" :column="2" border label-class-name="my-label">
        <el-descriptions-item label="会议主题">
          <span>{{ meetingVO.subject }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="附件">
          <el-link v-for="item in meetingVO.meetingAttachments" :key="item.id" :href="item.filePath"
                   target="_blank" style="margin-right: 5px">{{ item.filePath.split('/').pop() }}
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          <span>{{ meetingVO.startTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          <span>{{ meetingVO.endTime }}</span>
        </el-descriptions-item>
        <!--        <el-descriptions-item label="会议地址">
                  <span>{{ meetingVO.address }}</span>
                </el-descriptions-item>-->
        <el-descriptions-item label="主持人">
          <span>{{ meetingVO.host }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="参会人员">
          <span v-for="(item, index) in meetingVO.meetingAttendeesList" :key="index" style="margin-right: 5px">
                {{ item.name }}
              </span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="会议议程">
          <el-table :data="meetingVO.meetingAgendaList" size="mini" :border="false">
            <el-table-column label="序号" type="index" min-width="10%" header-align="center"></el-table-column>
            <el-table-column label="内容" prop="agenda" min-width="80%" header-align="center"></el-table-column>
            <el-table-column label="主持人" prop="host" min-width="10%" header-align="center"></el-table-column>
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="会议要求">
          <span>{{ meetingVO.requirement }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-form size="mini" label-position="top" label-width="8rem" style="margin-top: 20px">
        <el-form-item label="上次会议工作" v-if="meetingVO.categoryId = 4 ">
          <el-table ref="table"
                    row-key="id" border
                    :data="lastMeetingDecisions">
            <el-table-column label="序号" min-width="8%" type="index" header-align="center"></el-table-column>
            <el-table-column label="工作内容" prop="decision" min-width="32%" header-align="center"></el-table-column>
            <el-table-column label="完成情况" class-name="customColumn" min-width="60%" header-align="center">
              <template slot-scope="scope">
                <el-table :size="size" border="none" :data="scope.row.completeSummaries" :show-header="false" :border="false"
                          style="margin: 0; width: 100%">
                  <el-table-column prop="weekLabel" width="50px" v-if="false"></el-table-column>
                  <el-table-column>
                    <template slot-scope="innerScope">
                      <el-input
                          v-model="innerScope.row.taskComplete"
                          size="mini"
                          :disabled="!editVisible"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column width="140px">
                    <template slot-scope="innerScope">
                        <span style="font-style: italic; size: 10px">{{ innerScope.row.createBy }}&nbsp;&nbsp;{{
                            innerScope.row.createTime
                          }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="editVisible" width="80px">
                    <template slot-scope="innerScope">
                      <el-button v-if='innerScope.row.taskComplete.trim()!=""' type="text"
                                 @click="submitLastMeetingDecisions(scope.row.taskId ,innerScope.row)"
                                 icon="el-icon-check">提交
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <el-form size="mini" label-position="top" label-width="8rem">
        <el-form-item label="本次会议议题">
          <el-table ref="table"
                    row-key="id"
                    :data="meetingTasks"
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column label="序号" min-width="8%" type="index" header-align="center"></el-table-column>
            <el-table-column label="内容" min-width="27%" header-align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.record"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="决议" min-width="27%" header-align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.decision"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="提案人" prop="recorder" min-width="9%" header-align="center"></el-table-column>
            <el-table-column label="完成时间"  min-width="12%" header-align="center">
              <template slot-scope="scope">
                <el-date-picker class="el-date-editor"
                                type="date"
                                size="mini"
                                v-model="scope.row.endTime"
                                @change="updateMeetingTask(scope.row)"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="负责人" min-width="9%" header-align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.reportBy"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="selection" min-width="8%" header-align="center"></el-table-column>
          </el-table>
          <!--            <el-button type="text" @click="addMeetingRecordRow">
                        <i class="el-icon-plus"></i>增加行
                      </el-button>-->
          <el-button type="text" @click="deleteSelectedRows" icon="el-icon-minus" size="mini"></el-button>
          <el-button type="text" @click="submitMeetingDecision" icon="el-icon-check" size="mini">保存决议</el-button>
          <el-button type="text" @click="applyMeetingTask" icon="el-icon-s-flag" size="mini">发布任务</el-button>
        </el-form-item>
      </el-form>
      <el-form label-position="top" label-width="8rem" size="mini">
        <el-form-item label="下一阶段工作安排">
          <div style="border: 1px solid #eee; background-color: #fff;">
            <el-table row-key="id"
                      :data="usualMeetingTasks"
                      border @selection-change="handleSelectionChange">
              <el-table-column label="序号" min-width="8%" type="index" header-align="center"></el-table-column>
              <el-table-column label="内容" min-width="63%" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.decision"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="完成时间" min-width="12%" header-align="center">
                <template slot-scope="scope">
                  <el-date-picker class="el-date-editor"
                                  type="date"
                                  size="mini"
                                  v-model="scope.row.endTime"
                                  @change="updateMeetingTask(scope.row)"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="责任人" min-width="9%" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.reportBy"></el-input>
                </template>
              </el-table-column>
              <el-table-column type="selection" min-width="8%" header-align="center"></el-table-column>
            </el-table>
            <el-button type="text" @click="addRow" icon="el-icon-plus"></el-button>
            <el-button type="text" @click="deleteRow" icon="el-icon-minus"></el-button>
            <el-button type="text" @click="releaseUsualMeetingTask" icon="el-icon-s-flag">发布任务</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <Calendar></Calendar>
  </div>
</template>

<script>
import Sortable from 'sortablejs';
import moment from 'moment';
import Calendar from '@/components/Calendar.vue';

export default {
  name: 'MeetingDetail',
  components: {Calendar},
  data() {
    return {
      selectedRows: [],
      meetingId: '',
      meetingVO: {
        name: '',
        categoryId: '',
        subject: '',
        startTime: '',
        endTime: '',
        address: '',
        host: '',
        meetingAttendeesList: [{name: ''}],
        meetingAgendaList: [{agenda: '', host: ''}],
        requirement: '',
        meetingAttachments: []
      },
      lastMeetingDecisions: [{
        decision: '',
        completeSummaries: [{weekLabel: '', taskComplete: '', createTime: '', createBy: ''}]
      }],
      sortable: null,
      meetingRecord: [{id: '', content: '', recorder: '', createTime: ''}],
      userName: '',
      meetingTasks: [],
      usualMeetingTasks: [],
      multipleSelection: [],
      size: 'mini',
      editVisible: false,
    };
  },
  methods: {
    addMeetingRecordRow() {
      // 生成唯一 id（基于当前最大 id 或时间戳）
      const newId = this.meetingTasks.length
          ? Math.max(...this.meetingTasks.map(task => task.id), 0) + 1
          : 1;
      this.meetingTasks.push({
        id: newId,
        record: '',
        recorder: this.userName,
        decision: '',
        endTime: '',
        reportBy: '',
        startTime: '',
        reportCount: '',
        frequency: '周',
        sort: ''
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    deleteSelectedRows() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的行');
        return;
      }
      this.selectedRows.forEach(row => {
        const index = this.meetingTasks.indexOf(row);
        if (index > -1) {
          this.meetingTasks.splice(index, 1);
        }
      });
      this.selectedRows = [];
    },
    updateMeetingTask(row) {
      let startTime = '';
      let endTime = '';
      let reportCount = 0;
      if (row.endTime && row.frequency) {
        const currentDate = new Date();
        startTime = moment(currentDate).format('YYYY/MM/DD HH:mm:ss');
        endTime = moment(row.endTime).format('YYYY/MM/DD HH:mm:ss');
        const startDate = currentDate;
        const endDate = new Date(row.endTime);
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        const adjustedDiffDays = diffDays === 0 ? 1 : diffDays;
        switch (row.frequency) {
          case '天':
            reportCount = adjustedDiffDays;
            break;
          case '周':
            reportCount = Math.ceil(adjustedDiffDays / 7);
            break;
          case '月':
            const months =
                (endDate.getFullYear() - startDate.getFullYear()) * 12 +
                (endDate.getMonth() - startDate.getMonth());
            reportCount = Math.ceil(months);
            break;
          default:
            reportCount = 0;
        }
      }
      row.startTime = startTime;
      row.reportCount = reportCount;
    },
    submitMeetingDecision() {
      // 校验每一行的决议不能为空
      const emptyDecisionRow = this.meetingTasks.find(row => !row.decision || row.decision.trim() === '');
      if (emptyDecisionRow) {
        this.$message({
          type: 'warning',
          message: '决议内容不能为空',
          showClose: true,
        });
        return;
      }
      const meetingDecisionDTOS = this.meetingTasks.map(row => ({
        meetingId: this.meetingId,
        recordId: row.id,
        decision: row.decision
      }));
      console.log(meetingDecisionDTOS)
      this.$http.post("/meeting/decision/", meetingDecisionDTOS).then(response => {
        if (response.data.code == 1) {
          this.$message({
            type: 'success',
            message: "决议保存成功",
            showClose: true,
          });
        } else {
          this.$message({type: 'error', message: '保存失败:', showClose: true});
        }
      });
    },
    applyMeetingTask() {
      // 先校验是否有选中行
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一行决议内容进行发布！',
          showClose: true,
        });
        return;
      }
      // 校验选中行的完成时间和负责人不能为空
      const invalidRow = this.selectedRows.find(row => !row.endTime || !row.reportBy || row.reportBy.trim() === '');
      if (invalidRow) {
        this.$message({
          type: 'warning',
          message: '"完成时间"或"负责人"不能为空',
          showClose: true,
        });
        return;
      }
      const meetingTasks = this.selectedRows.map(row => ({
        ...row,
        title: this.meetingVO.name,
        contentSummaries: row.decision ? [{contentSummary: row.decision}] : [],
        endTime: moment(row.endTime).format('YYYY/MM/DD HH:mm:ss'),
        decisionId: row.decisionId,
        categoryId:4,
      }));
      this.$http.post('/task/record/release/', meetingTasks).then(response => {
        if (response.data.code == 1) {
          console.log(JSON.stringify(meetingTasks, null, 2))
          this.$message({
            type: 'success',
            message: `发布成功:任务办理人${this.meetingVO.meetingAttendeesList}`,
            showClose: true,
          });
        } else {
          this.$message({type: 'error', message: '发布失败:', showClose: true});
        }
      });
    },
    moveArrayElement(array, oldIndex, newIndex) {
      if (oldIndex < 0 || oldIndex >= array.length || newIndex < 0 || newIndex >= array.length) {
        console.error('Invalid index:', {oldIndex, newIndex, arrayLength: array.length});
        return;
      }
      const element = array.splice(oldIndex, 1)[0];
      array.splice(newIndex, 0, element);
      // 强制触发响应式更新
      this.meetingTasks = [...this.meetingTasks];
    },
    initDragSortTableRow() {
      const tbody = this.$refs.table.$el.querySelector('.el-table__body-wrapper > table > tbody');
      this.sortable = Sortable.create(tbody, {
        animation: 150,
        ghostClass: 'ghostClass',
        onEnd: e => {
          const {oldIndex, newIndex} = e;
          this.moveArrayElement(this.meetingTasks, oldIndex, newIndex);
          this.saveSortOrder(); // 保存新排序到后端
        },
      });
    },
    saveSortOrder() {
      const meetingRecordSortDTOS = this.meetingTasks.map((record, index) => ({
        id: record.id,
        sort: index + 1,
      }));
      this.$http.post('/meeting/record/sort/', meetingRecordSortDTOS).then(response => {
      }).catch(err => {
        this.$message.error('排序失败');
      });
    },
    addRow() {
      const newId = this.usualMeetingTasks.length
          ? Math.max(...this.usualMeetingTasks.map(item => item.id)) + 1
          : 1;
      this.usualMeetingTasks.push({
        id: newId,
        decision: '',
        endTime: '',
        reportBy: '',
        startTime: '',
        reportCount: '',
        frequency: '周',
      });
    },
    deleteRow() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的行');
        return;
      }
      this.usualMeetingTasks = this.usualMeetingTasks.filter(
          item => !this.selectedRows.includes(item)
      );
      this.selectedRows = [];
    },
    releaseUsualMeetingTask() {
      // 先校验是否有选中行
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一行决议内容进行发布！',
          showClose: true,
        });
        return;
      }
      // 校验选中行的完成时间和负责人不能为空
      const invalidRow = this.selectedRows.find(row => !row.endTime || !row.reportBy || row.reportBy.trim() === '');
      if (invalidRow) {
        this.$message({
          type: 'warning',
          message: '"完成时间"或"负责人"不能为空',
          showClose: true,
        });
        return;
      }
      const meetingDecisionDTOS = this.selectedRows.map(row => ({
        meetingId: this.meetingId,
        recordId: 0,
        rowId: row.id,
        decision: row.decision
      }));
      console.log(JSON.stringify(meetingDecisionDTOS, null, 2))
      this.$http.post('/meeting/usual_decision/', meetingDecisionDTOS)
          .then(res => {
            // 假设后端返回 [{rowId: 1, decisionId: 101}, ...]
            const mapping = res.data.data;
            console.log(mapping)
            // 用 rowId -> decisionId 的映射补全 meetingTasks
            const meetingTasks = this.selectedRows.map(row => {
              const found = mapping.find(m => m.rowId === row.id);
              return {
                ...row,
                decisionId: found ? found.decisionId : null, // 补上 decisionId
                contentSummaries: row.decision ? [{contentSummary: row.decision}] : [],
                endTime: moment(row.endTime).format('YYYY/MM/DD HH:mm:ss'),
                meetingId: this.meetingVO.id,
                title: row.decision,
                categoryId:4,
              };
            });
            console.log(JSON.stringify(meetingTasks, null, 2))
            // 再发任务
            return this.$http.post('/task/record/release/', meetingTasks);
          })
          .then(() => {
            this.$message.success('发布成功');
          })
          .catch(() => {
            this.$message.error('发布失败');
          });
    },
    checkPermissions() {
      const userInfo = JSON.parse(localStorage.getItem('user'))
      this.editVisible = (userInfo.username === 'cfswt' || userInfo.username === 'renting')
    },
    submitLastMeetingDecisions(taskId, completeData) {
      // 所有验证通过，提交数据
      if (completeData.taskComplete.trim() !== "") {
        const lastMeetingComplete = {
          ...completeData,
          weekLabel: 1,
          createBy: '任婷',
          createTime: moment(new Date()).format('YYYY/MM/DD HH:mm:ss'),
          taskId: taskId
        }
        console.log(JSON.stringify(lastMeetingComplete, null, 2))
        this.$http.post('/meeting/last_decision/complete/', lastMeetingComplete)
            .then(() => {
              this.$message.success('保存成功');
            })
            .catch(() => {
              this.$message.error('保存失败');
            });
      } else {
        this.$message.error("完成任务内容不能为空")
      }
    }
  },
  created() {
    this.userName = JSON.parse(localStorage.getItem('user')).nickName;
    this.meetingId = this.$route.query.meetingId;
    this.$http.get(`/meeting/detail_inList/${this.meetingId}`).then(response => {
      if (response.data.code == 1) {
        this.meetingVO = response.data.data;
        console.log(`会议数据:${JSON.stringify(this.meetingVO, null, 2)}`);
      } else {
        this.$message({type: 'error', message: '发布失败:', showClose: true});
      }
    });
// 获取议题和决策数据
    Promise.all([
      this.$http.get(`/meeting/record/${this.meetingId}`),
      this.$http.get(`/meeting/decision/${this.meetingId}`)
    ]).then(([recordRes, decisionRes]) => {
      if (recordRes.data.code == 1 && decisionRes.data.code == 1) {
        const records = recordRes.data.data; // 议题列表
        const decisions = decisionRes.data.data; // 决策列表
        // 以recordId为key，构建决策Map
        console.log(`本次会议议案数据:${JSON.stringify(records, null, 2)}`)
        console.log(`本次会议决策数据:${JSON.stringify(decisions, null, 2)}`)
        this.usualMeetingTasks = decisions.filter(item => item.recordId === 0);
        const decisionMap = {};
        decisions.forEach(item => {
          // 存储决策内容和决策id
          decisionMap[item.recordId] = {
            decision: item.decision,
            decisionId: item.id,
            endTime: item.endTime,
            reportBy: item.reportBy
          };
        });
        // 合并数据
        const newMeetingTasks = records.map(record => {
          const decisionObj = decisionMap[record.id] || {};
          return {
            id: record.id || Date.now() + Math.random(), // 确保 id 唯一
            record: record.content,
            recorder: record.recorder,
            decision: decisionObj.decision || '', // 决策内容
            decisionId: decisionObj.decisionId || '', // 决策id
            endTime: decisionObj.endTime,
            reportBy: decisionObj.reportBy,
            startTime: '',
            reportCount: '',
            frequency: '周',
            sort: record.sort
          };
        });
        this.$set(this, 'meetingTasks', newMeetingTasks);
        console.log(`整合后的议案和决议数据为：${JSON.stringify(newMeetingTasks, null, 2)}`)
        this.initDragSortTableRow();
      } else {
        this.$message({type: 'error', message: '获取会议记录或决策数据不成功:', showClose: true});
      }
    });
    this.$http.get(`/meeting/last_decision/${this.meetingId}`).then(response => {
      if (response.data.code == 1) {
        const meetingDecisionVOS = response.data.data
        meetingDecisionVOS.forEach(item => {
          if (!item.completeSummaries || item.completeSummaries.length === 0) {
            item.completeSummaries = [{
              weekLabel: '',
              taskComplete: '',
              createTime: '',
              createBy: ''
            }];
          }
        });
        this.lastMeetingDecisions = meetingDecisionVOS
        console.log(`上次会议决策以及完成内容:${JSON.stringify(this.lastMeetingDecisions, null, 2)}`);
      }
    })
    this.checkPermissions()
  },
}
</script>

<style scoped>

::v-deep .el-card__body {
  margin: 0;
  padding: 0;
}

::v-deep .el-card:nth-child(1).el-card__header {
  padding: 0 !important;
}

::v-deep .ghostClass {
  background-color: #ecf5ff;
}

::v-deep .ghostClass td {
  border-bottom-color: #409eff;
}

::v-deep .el-date-editor .el-input__prefix {
  display: none !important
}

::v-deep .customColumn > .cell {
  padding: 0px !important;
}
</style>
